package org.wkg;

public class HashBuck1 {

    public static class Node {
        public int key;
        public int val;
        public Node next;


        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] Array = new Node[10];
    public int useSize;
    public static final float LOAD_FACTOR = 0.75f;

    public void put(int key, int val) {
        int size = Array.length;
        int index = key % size;
        Node cur = Array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        Node node = new Node(key, val);
        node.next = Array[index];
        Array[index] = node;
        useSize++;


        if (doLoadFactor() > LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        Node[] nodeArray = new Node[Array.length * 2];
        int size = Array.length;
        for (int i = 0; i < Array.length; i++) {
            Node cur = Array[i];
            while (cur != null) {
                int newIndex = cur.key % nodeArray.length;
                Node curN = cur.next;
                cur.next = nodeArray[newIndex];
                nodeArray[newIndex] = cur;
                cur = curN;
            }
        }
        Array = nodeArray;
    }


    public float doLoadFactor() {
        return useSize * 1.0f / Array.length;
    }

    public int get(int key) {
        int size = Array.length;
        int index = key % size;
        Node cur = Array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }


}
